package com.nf;

import com.nf.entity.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

public class Test {

    public static void main(String[] args) {
        //第一步：需要一个配置类
        Configuration config = new Configuration();
        //第二步：对配置类加载一个配置文件
        config.configure();
        //非常慢
        SessionFactory factory = config.buildSessionFactory();
        //System.out.println("factory:"+factory);
        //第三步:通过Session的API，实现增删改查
        Session session = factory.openSession();
        //1.增
        //"insert into Student(..) values(?,?)"
        /*
        Student s1 = new Student();
        s1.setName("牛魔");
        s1.setSex("其它");

        session.save(s1);
        */
        //2.查询 Query query = session.createQuery("from Student ");
        //查询分2种：
        // 1.按HQL查询（n条记录）
        // 2.直接过ID指定获取一个实例
        //select * from t_student where id=3
        //Student ss = session.get(Student.class,3);
        //System.out.println(   ss.getName()  );

        //3.改
        /*
        ss.setName("小红");
        //这条语句不生效：session.update(ss);
        session.beginTransaction();
        //事务里往往是多条执行语句
        //(要么全部成功，要么全部失败)
        session.update(ss);


        session.getTransaction().commit();
        */
        //4.删
        /*
        session.beginTransaction();
        session.delete(ss);
        session.getTransaction().commit();
        */
        //5.感受一下事务的回滚

        session.beginTransaction();
        try{
            //...事务的代码段
            Student s1 = session.get(Student.class,1);
            Student s2 = session.get(Student.class,2);
            s1.setSex("女");
            s2.setSex("美颜后的女性");
            session.update(s1);
            session.update(s2);

            //如果全部成功，提交事务
            session.getTransaction().commit();
        }catch (Exception e){
            System.out.println("发生异常:"+e.getMessage());

            //如果有异常,事务回滚
            session.getTransaction().rollback();
        }




        session.close();
        factory.close();
    }
}
